<?php
namespace app\admin\controller;

use app\common\model\MealDetailModel;
use app\common\model\MealSpeciModel;
use app\common\controller\AdminController;
use app\common\model\MealModel;

use think\Db;

/**  YSF
 *   套餐管理 控制器
 *   Date: 2018/12/10
 * Class Meal
 * @package app\admin\controller
 */
class Meal extends AdminController
{
    protected $mealModel;
    protected $mealDetailModel;
    protected $mealSpeciModel;

    // 初始化构造方法
    public function __construct()
    {
        parent::__construct();
        // 加载套餐模型
        $this->mealModel = new MealModel();
        $this->mealDetailModel = new MealDetailModel();
        $this->mealSpeciModel = new MealSpeciModel();
    }

    // 套餐列表查询
    public function index()
    {
        // ajax访问
        if ($this->request->get('type') == 'ajax') {
            // 接收参数
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $select = (array)$this->request->get('select', []);

            $where = [['is_del', '=', 1]]; // 未被删除
            // 搜索条件
            foreach ($select as $k => $v)
            {
                if ($k == 'name' && $v != '') {
                    $where[] = [$k, 'LIKE', '%' . $v . '%'];
                }
            }
            $field = '*';
            $order = 'meal_id DESC';
            // 列表查询
            $data = $this->mealModel->getAll($where, $field, $page, $limit,[], $order);
            // 数量查询
            $count = $this->mealModel->getCount($where);
            // 数据组装
            $info = [
                'limit'        => $limit,
                'page_current' => $page,
                'page_sum'     => ceil($count / $limit),
            ];
            $msg = '暂无数据！';
            if ($data) {
                $msg = '查询成功！';
                foreach ($data as $k => &$v)
                {
                    $v['type_name'] = config('admin.meal_type')[$v['type']];
                    $v['status_name'] = config('admin.meal_status')[$v['status']];
                    $v['create_time'] = dateTime($v['create_time']);
                }
            }
            $list = [
                'code'  => 0,
                'msg'   => $msg,
                'count' => $count,
                'info'  => $info,
                'data'  => $data,
            ];
            return json($list);
        }

        // 基础数据
        $basic_data = [
            'title' => '管理员列表',
            'data'  => '',
        ];

        return $this->fetch('', $basic_data);
    }

    // 套餐添加操作
    public function add()
    {
        // 渲染添加页面
        if (!$this->request->isPost()) {
            //基础数据
            $basic_data = [
                'type' => config('admin.meal_type'),
            ];
            $this->assign($basic_data);
            return $this->fetch();
        }
        // 处理添加操作
        else {
            // 接收参数
            $post = $this->request->post();
            $post['create_time'] = time();
            // 详情数据
            $data['meal_detail'] = $post['meal_content'];
            $data['service_detail'] = $post['server_content'];
            $data['create_time'] = time();
            // 规格数据
            $speci = $post['speci'];
            unset($post['speci']);
            unset($post['meal_content']);
            unset($post['server_content']);
            // 开启事务
            Db::startTrans();
            try{
                // 1-- 添加套餐
                $meal_id = $this->mealModel->add($post);
                $data['meal_id'] = $meal_id;
                // 2-- 添加详情
                $this->mealDetailModel->add($data);
                // 3-- 添加规格
                foreach ($speci as $k => $v)
                {
                    $speci_data['meal_id'] = $meal_id;
                    $speci_data['name'] = $v['norms_name'];
                    $speci_data['img'] = $v['norms_pic'];
                    $speci_data['sales'] = $v['norms_sales'];
                    $speci_data['stock'] = $v['norms_stock'];
                    $speci_data['oPrice'] = formatMoney($v['norms_oPrice'], 1);
                    $speci_data['sPrice'] = formatMoney($v['norms_sPrice'], 1);
                    $speci_data['create_time'] = time();
                    $this->mealSpeciModel->add($speci_data);
                }

                // 事务提交
                Db::commit();
                $res = true;
            } catch (\Exception $e) {
                // 事务回滚
                Db::rollback();
                $res = false;
            }

            if ($res) {
                return json(['code' => 1, 'msg' => '添加成功']);
            }
                return json(['code' => 0, 'msg' => '添加失败']);
        }
    }

    // 套餐编辑操作
    public function edit()
    {
        // 渲染编辑页面
        if (!$this->request->isPost()) {
            // 接收参数
            $id = $this->request->get('id');
            $join = [
                ['set_meal_detail md', 'md.meal_id = a.meal_id', 'left']  // 套餐详情--套餐
            ];
            $where['a.meal_id'] = $id;
            $field = '*';
            // 获取套餐信息
            $data = $this->mealModel->getOne($where,$field,$join);
            unset($where);
            if (empty($data)) return msg_error('暂无数据，请重新刷新页面！');
            $data['image_url'] = config('api.qi_niu_url').$data['image'];
            // 获取规格数据
            $where['meal_id'] = $id;
            $speci = $this->mealSpeciModel->getAll($where);

            unset($where);
            if (!empty($speci)) {
                foreach ($speci as $k => &$v)
                {
                    if (!empty($v['img'])) {
                        $speci[$k]['img_url'] = config('api.qi_niu_url').$v['img'];
                    }
                    $speci[$k]['oPrice'] = formatMoney($v['oPrice']);
                    $speci[$k]['sPrice'] = formatMoney($v['sPrice']);
                }
            }
            $data['speci']=$speci;
            // 基础数据
            $basic_data = [
                'type' => config('admin.meal_type'),
                'data'  => $data,
            ];
            $this->assign($basic_data);
            return $this->fetch('add');
        }
        // 处理编辑操作
        else {
            // 接收参数
            $post = $this->request->post();
            //清空菜单缓存
            clear_menu();

            $where['meal_id'] = $post['id'];
            // 详情数据
            $data_where['meal_id'] = $post['id'];
            $data['meal_detail'] = $post['meal_content'];
            $data['service_detail'] = $post['server_content'];
            // 规格数据
            $speci = $post['speci'];
            $speci_data['meal_id'] = $post['id'];
            unset($post['speci']);
            unset($post['id']);
            unset($post['meal_content']);
            unset($post['server_content']);

            // 开启事务
            Db::startTrans();
            try{
                // 1-- 修改套餐
                $this->mealModel->edit($where, $post);
                unset($where);
                // 2-- 修改详情
                $this->mealDetailModel->edit($data_where, $data);
                unset($data_where);
                // 3-- 修改规格
                foreach ($speci as $k => $v)
                {
                    $speci_data['name'] = $v['norms_name'];
                    $speci_data['img'] = $v['norms_pic'];
                    $speci_data['sales'] = $v['norms_sales'];
                    $speci_data['stock'] = $v['norms_stock'];
                    $speci_data['oPrice'] = formatMoney($v['norms_oPrice'], 1);
                    $speci_data['sPrice'] = formatMoney($v['norms_sPrice'], 1);
                    // 添加
                    if (empty($v['id'])) {
                        $speci_data['create_time'] = time();
                        $this->mealSpeciModel->add($speci_data);
                    }
                    // 修改
                    else {
                        $speci_where['id'] = $v['id'];
                        $speci_where['meal_id'] = $v['meal_id'];
                        $this->mealSpeciModel->edit($speci_where, $speci_data);
                        unset($speci_where);
                    }
                }

                // 事务提交
                Db::commit();
                $res = true;
            } catch (\Exception $e) {
                Db::rollback();
                $res = false;
            }

            if ($res) {
                return json(['code' => 1, 'msg' => '编辑成功']);
            }
                return json(['code' => 0, 'msg' => '编辑失败']);
        }
    }

    // 套餐状态操作
    public function status()
    {
        // 接收参数
        $get = $this->request->get();

        //验证数据
        $validate = $this->validate($get, 'app\admin\validate\Meal.status');
        if (true !== $validate) return __error($validate);

        $where['meal_id'] = $get['id'];
        $value = 'status';
        // 获取状态值
        $status = $this->mealModel->getValue($where, $value);
        $status == 1 ? list($msg, $status) = ['切换成功', $status = 2] : list($msg, $status) = ['切换成功', $status = 1];

        //执行更新操作操作
        $data['status'] = $status;
        $update = $this->mealModel->edit($where, $data);
        unset($where);

        //清空菜单缓存
        clear_menu();

        if ($update >= 1) return __success($msg);
        return __error('数据有误，请刷新重试！');

    }

    // 套餐删除
    public function del()
    {
        // 接收参数
        $get = $this->request->get();

        // 验证数据
        if (!is_array($get['id'])) {
            $validate = $this->validate($get, 'app\admin\validate\Meal.del');
            if (true !== $validate) return __error($validate);
        }

        $del = 0;
        // 批量删除操作
        if (is_array($get['id'])) {
            foreach ($get['id'] as $k => $v)
            {
                $where['meal_id'] = $v;
                $data['is_del'] = 2;
                $del = $this->mealModel->edit($where, $data);
                unset($where);
            }
        }
        // 单条删除
        else {
            $where['meal_id'] = $get['id'];
            $data['is_del'] = 2;
            $del = $this->mealModel->edit($where, $data);
            unset($where);
        }

        if ($del >= 1) {
            //清空菜单缓存
            clear_menu();
            return __success('删除成功！');
        } else {
            return __error('数据有误，请刷新重试！');
        }
    }



}